<?php
/*
 * Copyright (c) 2009 Tom Smith (tom@takeontom.com).
 * 
 * Distributed under the terms of the GNU Lesser General Public License.
 * 
 * ---------------------------------------------------------------------------------
 * 
 * This file is part of Seraph PHP Framework.
 *
 * Seraph PHP Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Seraph PHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Seraph PHP Framework.  If not, see <http://www.gnu.org/licenses/>.
*/


class IncludePathAutoloader implements IAutoloader	{
	protected $targetDirs;
	protected $includePathConfigured = false;
	protected $originalIncludePath;
	
	public function __construct(array $targetDirs)	{
		$this->setTargetDirs($targetDirs);
	}
	
	public function setTargetDirs(array $targetDirs)	{
		$this->targetDirs = $targetDirs;
		
		$this->addTargetDirsToIncludePath($targetDirs);
	}
	
	public function addTargetDirs(array $targetDirs)	{
		$this->targetDirs = array_merge($this->targetDirs, $targetDirs);
		$this->addTargetDirsToIncludePath($targetDirs);
	}
	
	public function getTargetDirs()	{
		return $this->targetDirs;
	}
	
	public function loadClass($className)	{
		$filename = $className . '.php';
		
		//go through include paths to try and find class file
		foreach(explode(PATH_SEPARATOR, get_include_path()) as $path)	{
			if (file_exists($path . '/' . $filename))	{
				include $filename;
				return true;
			}
		}
		
	}
	
	public function addTargetDirsToIncludePath(array $dirs)	{
		
		/*
		if (!isset($this->originalIncludePath))	{
			$this->originalIncludePath = get_include_path();
		}
		*/
		
		$initialPath = get_include_path();
		
		$extraInclude = '';
		foreach($dirs as $aDir)	{
			
			
			$extraInclude .= realpath($aDir) . PATH_SEPARATOR;
			
			$dirIterator = new RecursiveDirectoryIterator($aDir);
			$iterator = new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST);
			
			foreach($iterator as $file)	{
				
				if ($file->isDir())	{
					$extraInclude .= $file->getRealPath() . PATH_SEPARATOR;
				} else {
					
				}
			}
			
		}
		
		set_include_path($extraInclude . $initialPath);
	}
	
	
}
?>